import {
  asyncRouterMap,
  constantRouterMap
} from '@/router/index'
import MenuType from '@/utils/menuType'
import Layout from '@/views/layout/Layout'
import GroupLayout from '@/views/layout/GroupLayout'
const _import = require('@/router/import_' + process.env.NODE_ENV).default

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission (roles, route) {
  if (route.meta && route.meta.role) {
    return roles.some(role => route.meta.role.indexOf(role) >= 0)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter (asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      // var temp = routers.slice(0);
      // var filterFunc = (self,router) =>{
      //   if (router.children && router.children.length>0) {
      //     router.children = router.children.filter(child=>{
      //       return self(self,child);
      //     });
      //     return true;
      //   }
      //   else if (router.component == Layout) {
      //     return false;
      //   }
      //   else{
      //     return true;
      //   }
      // };
      // state.addRouters = routers.filter(router=>{
      //   return filterFunc(filterFunc,router);
      // });
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes ({
      commit
    }, data) {
      return new Promise(resolve => {
        const {
          roles,
          menus
        } = data
        let accessedRouters
        if (roles.indexOf('admin') >= 0) {
          accessedRouters = asyncRouterMap
        } else {
          accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
        }

        var recursiveFunc = (self, menu) => {
          var subrouters = []
          if (menu.children) {
            subrouters = menu.children.map(subobj => self(self, subobj))
          }

          var {
            id,
            path,
            name,
            type,
            icon,
            children = subrouters
          } = menu
          if (subrouters && subrouters.length > 0) {
            children = subrouters
          }
          var redirect = ''
          var component
          var props = false
          if (menu.type === MenuType.Router || menu.type === MenuType.Hidden) {
            var re = /\/:\S*/
            var componentPath = path.replace(re, '')
            props = true
            // props = componentPath != path || menu.type == 3
            // path = componentPath;
            try {
              component = _import(componentPath)
            } catch (error) {
              console.debug(error)
              component = _import('/404')
            }
          } else {
            redirect = 'noredirect'
            if (menu.type === MenuType.Expandable) {
              component = Layout
            } else {
              component = GroupLayout
            }
          }
          var noDropdown = subrouters.length <= 0
          return {
            meta: { id },
            path,
            name,
            type,
            icon,
            hidden: false,
            noDropdown,
            redirect,
            children,
            component,
            props
          }
        }

        var routers = menus.map(menu => {
          return recursiveFunc(recursiveFunc, menu)
        })

        routers.forEach(element => {
          if (!element || element === undefined) {

          }
          // accessedRouters.unshift(element);
        })
        routers = routers.concat(accessedRouters)

        commit('SET_ROUTERS', routers)
        resolve()
      })
    }
  }
}

export default permission
